<? if ($c = stack('name')) {
	
	require_once('_lib/formvalidator.php');

	
	$fields = array(
		'region_id' => 'req:Потрібно обрати',
		'issue' => 'req:Потрібно заповнити',
	);
	
	$_values	= array('question_id', 'region_id', 'issue', /*'department_id',*/ 'target');

	$uuid = gccGetUUID();
	$now = parse_today();
	foreach(str_split('dmhMs') as $v) $now[$v] = d2d($now[$v]);
	$now = "$now[d].$now[m].$now[y]:$now[h]:$now[M]:$now[s]";

	$_record = array('id' => $uuid, 'create_date' => $now, 'person_id' => gccUserInfo('person_id'));
//debug($_record);				


	if (($uuid = gccHuuid(param('send'))) && ($d = datafetch('db_item', 'cs_claim', "id=$uuid"))) {

		foreach($_values as $v) $_record[$v] = $d[$v];
		
		unset($_record['id']);

//debug($_record);
		$val = gccClaimStore($_record);
//debug($val);			
		if ($val['stored']) {
			
			dataset('db_delete', 'cs_claim', "id=$uuid");
			
			header("Location: "._transformURL($CURRENT->url, array('remove_params' => 'all', 'add_level' => 'sent')));
			exit;
		
		} else {
		
			header("Location: "._transformURL($CURRENT->url, array('remove_params' => 'all', 'add_level' => 'not_sent')));
			exit;
		}

	}


	
	switch (postdata('submit_type')) {
		
		case 'save':
		
			$val = new FormValidator();
			
			foreach($fields as $f => $v) 
				foreach(explode(',', $v) as $rule) {
					$r = explode(':', $rule);
					$val->addValidation($f, $r[0], $r[1]);
				}
		
		//dbdebug(1,1);
			
			if ($val->ValidateForm()) {
				
				foreach($_values as $v) $_record[$v] = trim(postdata($v));
//dbdebug();				
				$claim_id = datafetch('db_insert', 'cs_claim', $_record);

				$res = array();
				foreach($_values as $v)
					$res[] = array($v, true, '');

				$res[] = array('id', true, $claim_id);
				
				print(json_encode($res));
				exit;
			
			} else {
				
				$r = array();
			
				$res = $val->GetErrors();
				foreach($res as $f => $e)
					if (isset($r[$f]))
						$r[$f][2] .= " $e";
					else
						$r[$f] = array($f, false, $e);
				
				$res = array();
				foreach($r as $v)
					$res[] = $v;
					
				print(json_encode($res));
				exit;
			}
		
			break;
			
		case 'send':

			foreach($_values as $v) $_record[$v] = trim(postdata($v));
			
			unset($_record['id']);
//debug($_record);
			$val = gccClaimStore($_record);
//debug($val);			
			if ($val['stored']) {
				
				$res = array();
				foreach($_values as $v)
					$res[] = array($v, true, '');
				
				print(json_encode($res));
				exit;
			
			} else {
			
				print($val['raw']);
				exit;
			}
			break;
	}

unstack();
}